'use strict';
var router    = require('express').Router();

var ErrorCode = require('./sqlapis/err');
var User      = require('./sqlapis/api_users');
var Sms 	  = require('./sqlapis/api_sms');

var SmsApi = require('./api_sms');
var ComFunc   = require('./comfunc');
var fs = require('fs');
var url    = require('url');

/*
修改用户信息
*/
router.post('/editusermessage',ComFunc.tokenCheck,function(req,res){
	var data = req.body;
	User.getUserId(data.sessiontoken,function(err,result){
		if(err){
			res.send(err)
		}else{
			var params = {
				user_id: result.user_id,
			}
			if(data.sex){
				params.sex = data.sex;
			}
			if(data.headimg){
				params.headimg = data.headimg;
			}
			if(data.nickname){
				params.nickname = data.nickname;
			}
			if(data.email){
				params.email = data.email;
			}
			if(data.phone){
				params.phone = data.phone
			}
			
			User.editUserMessage(params,function(result){
				res.send(result)
			})
		}
	})
})

router.post('/deluser',function(req,res){
	var data = req.body;
	if (!data.phone) {
		res.send(ErrorCode.noParams);
	}
	User.delUser(data,function(err,result){
		if(err){
			res.send(err)
		}else{
			res.send(ErrorCode.true)
		}
	})
})

/*
获取用户信息
*/
router.post('/usermessage',ComFunc.tokenCheck,function(req,res){
	var data = req.body;
	User.getUserId(data.token,function(err,result){
		if(err){
			res.send(err)
		}else{
			var params = {
				user_id: result.id,
			}
			User.userMessage(params,function(result){
				res.send(result)
			})
		}
	})
})

/*
 * RegCheckIfUserExit,注册前查询用户是否存在;
 * 用户名，邮箱, 手机号是否重复,验证码是否正确
 */
// RegCheckIfUserExit 暂时取消
router.post('/userReg',function(req, res){
	var data = {
		name : req.body.name,
		password: req.body.password,
		phone:req.body.phone
	}
	User.createUser(data,function(err,result){
		if(err){
			res.send(err);
		}
		else{
			// var data = {
   			//   mobilenumber:req.body.phone,
   			//   code:req.body.vcode
            // }
            // Sms.delSms(data,function(){
            //   console.log('删除成功');
            // })
			res.send(result);
		}
	})
})

/*
 * 用户登录
 */

router.post('/login',function(req,res,next){
	var phone = req.body.phone;
	var password  = req.body.password;
	var data = {
		phone : phone,
		password:password
	}
	User.login(data,function(err,result){
		if(err){
			res.send(err);
		}
		else{
			res.send(result);
		}
	})
})

/*
 *  三方登陆
 */
router.post('/register',function(req,res,next){
	var datas = {
		qqOpenId : req.body.qqOpenId || '',
		weiboOpenId:req.body.weiboOpenId||'',
		weixinOpenId:req.body.weixinOpenId||'',
		avatar : req.body.avatar,
		username:req.body.username,
		nickname:req.body.nickname
	}
	User.thirdLogin(datas,function(err,result){
		if(!result){
			res.send(err);
		}
		else{
			res.send(result);
		}
	})
})

//修改密码
//checkVcodeAndParams 暂时去掉
router.post('/changepass',function(req,res){
    var data = {
      phone:req.body.phone,
      newpassword:ComFunc.md5String(req.body.newpassword)
    }
    if(!req.body.newpassword){
       res.send(ErrorCode.noParams);
    }else{
      User.changePassWordByVcode(data,function(result){
        	res.send(result)
      })
    } 
})

//修改密码
router.post('/changepassbyold',function(req,res){
	if(!req.body.oldpassword || !req.body.mobile_phone || !req.body.newpassword){
		res.send(ErrorCode.noParams)
		return ;
	}
    var data = {
      mobile_phone:req.body.mobile_phone,
      newpassword:ComFunc.md5String(req.body.newpassword),
      oldpassword:ComFunc.md5String(req.body.oldpassword)
    }
    if(!req.body.newpassword){
       res.send(ErrorCode.noParams);
    }else{
      User.changePassword(data,function(result){
        	res.send(result)
      })
    }
    
})

//检测验证码和手机号
function checkVcodeAndParams(req,res,next){
    var data = {
      key : req.body.mobile,
      text: req.body.vcode
    }
    if(!req.body.mobile || !req.body.vcode || !req.body.newpassword){
      res.send(ErrorCode.noParams);
    }else{
      Sms.checkVcode(data,function(result){
          if(result !='1' ){
              res.send(ErrorCode.errVcode)
          }else{
            next();
          }
      });
    }
}

//注册时检查当前用户是否存在
function RegCheckIfUserExit(req, res, next){
	var name = req.body.name;
	var password = req.body.password;
	var phone = req.body.phone;
	var vcode = req.body.vcode;

	if(!name || !password || !phone || !vcode)
	{
		if(!name){res.send(ErrorCode.noUsername)} 
		else if(!password){res.send(ErrorCode.noPassword)}
		else if(!phone){res.send(ErrorCode.noMobile)}
		else if(!vcode){res.send(ErrorCode.noVcode)}
	}
	else{
		Promise.all([
			SmsApi.checkWithOneParam('name',name),
			SmsApi.checkWithOneParam('phone',phone),
			checkVcode(phone,vcode),
		]).then(function(r0){
			if((r0[0] == '1') || (r0[1] == '1')){
				if(r0[0] == '1'){res.send(ErrorCode.sameUsername)} 
				else if(r0[1] == '1'){res.send(ErrorCode.sameMobile)}
			}else{
				if( r0[2] != '1'){
					res.send(ErrorCode.errVcode);
				}
				else{
					next();
				}
			}
		})
	}
}

//验证码验证是否正确
function checkVcode(key,text){
	var promise = new AV.Promise(function(resolve,reject){
		var data = {
			key : key,
			text: text
		}
		Sms.checkVcode(data,function(result){
			resolve(result);
		});
	});
	return promise;
}

module.exports = router;